public class Main {
    private int[] items = new int[1000];
    volatile private int head = 0;
    volatile private int tail = 0;
    volatile private int size = 0;

    synchronized public void put(int elem) throws InterruptedException {
        while (size == items.length){
            this.wait();
        }
        items[tail] = elem;
        tail++;
        if (tail == items.length){
            tail = 0;
        }
        size++;
        this.notify();
    }

    synchronized public Integer take() throws InterruptedException {
        while (size == 0){
            this.wait();
        }
        int value = items[head];
        head++;
        if (head == items.length){
            head = 0;
        }
        size--;
        this.notify();
        return value;
    }
}

class Demo{
    public static void main(String[] args) {
        Main queue = new Main();
        Thread t1 = new Thread(()->{
            while (true){
                try {
                    int value = queue.take();
                    System.out.println("消费："+ value);
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        Thread t2 = new Thread(()->{
            int value = 0;
            while (true){
                try {
                    System.out.println("生产:" + value);
                    queue.put(value);
                    value++;
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();

    }
}
